package com;

import lombok.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.Pattern;
import java.util.stream.*;

/**
 * 企业级组件化框架 - 全面实现
 * 核心设计理念：
 * 1. 组件化定义式开发（业务组件 + 技术组件）
 * 2. 强类型系统保障安全
 * 3. 配置化工作流编排
 * 4. 注解驱动的校验机制
 * 5. 可扩展的技术基础设施
 */
public class EnterpriseComponentFramework {

    public static void main(String[] args) {
        runFrameworkDemo();
    }

    public static void runFrameworkDemo() {
        System.out.println("===== 企业级组件化框架演示 =====");
        
        // 1. 初始化框架核心
        ComponentRegistry registry = new ComponentRegistry();
        WorkflowEngine workflowEngine = new WorkflowEngine(registry);
        
        // 2. 注册技术组件
        registry.register(new ValidationComponent(), "validation");
        registry.register(new EncryptionComponent(), "encryption");
        registry.register(new LoggingComponent(), "logging");
        registry.register(new CachingComponent(new CacheManager()), "caching");
        registry.register(new AsyncExecutorComponent(), "asyncExecutor");
        
        // 3. 注册业务组件
        registry.register(new UserRegistrationComponent(), "userRegistration");
        registry.register(new OrderProcessingComponent(), "orderProcessing");
        registry.register(new PaymentProcessingComponent(), "payment");
        
        // 4. 创建工作流定义
        Workflow userWorkflow = new Workflow("user-registration")
            .addStep("参数校验", "validation", Map.of("strictMode", true))
            .addStep("用户注册", "userRegistration", Map.of())
            .addStep("记录日志", "logging", Map.of("logLevel", "INFO"));
        
        // 5. 创建订单工作流
        Workflow orderWorkflow = new Workflow("order-processing")
            .addStep("参数校验", "validation", Map.of("groups", "order"))
            .addStep("创建订单", "orderProcessing", Map.of())
            .addStep("支付处理", "payment", Map.of("async", true))
            .addStep("缓存结果", "caching", Map.of("ttl", 600));
        
        // 6. 准备用户注册请求
        UserRegistrationRequest userRequest = new UserRegistrationRequest();
        userRequest.setUsername("john_doe");
        userRequest.setPassword("Secure@123");
        userRequest.setPasswordConfirm("Secure@123");
        userRequest.setEmail("john@example.com");
        userRequest.setBirthDate("1990-05-15");
        
        // 7. 执行用户注册工作流
        ComponentOutput<UserRegistrationResponse> userOutput = workflowEngine.execute(userWorkflow, new ComponentContext<>(userRequest));
        
        System.out.println("\n=== 用户注册结果 ===");
        processOutput(userOutput);
        
        // 8. 准备订单请求
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.setUserId("user-123");
        orderRequest.setItems(Arrays.asList("item1", "item2", "item3"));
        orderRequest.setTotalAmount(150.99);
        orderRequest.setPaymentMethod("CREDIT_CARD");
        orderRequest.setCardNumber("4111111111111111");
        // 9. 执行订单处理工作流
        ComponentOutput<OrderResponse> orderOutput = workflowEngine.execute(orderWorkflow, new ComponentContext<>(orderRequest));
        
        System.out.println("\n=== 订单处理结果 ===");
        processOutput(orderOutput);
        
        // 10. 框架能力展示
        System.out.println("\n=== 框架能力展示 ===");
        registry.listComponents().forEach((name, type) -> 
            System.out.println("- " + name + ": " + type.getSimpleName()));
        
        System.out.println("===== 演示完成 =====");
    }

    private static void processOutput(ComponentOutput<?> output) {
        if (output.isSuccess()) {
            System.out.println("✅ 执行成功: " + output.getData());
        } else {
            System.out.println("❌ 执行失败: " + output.getErrorMessage());
            if (output.getValidationErrors() != null) {
                System.out.println(" 校验错误:");
                output.getValidationErrors().forEach(e ->
                        System.out.println(" - " + (e.getField() != null ? e.getField() + ": " : "") + e.getMessage()));
            }
        }
    }

}

// ====== 核心接口定义 ======

/**
 * 组件接口 - 业务组件和技术组件的统一接口
 * @param <I> 输入类型
 * @param <O> 输出类型
 */
interface Component<I, O> {
    String getType();
    ComponentOutput<O> execute(ComponentContext<I> context);
}

/**
 * 组件上下文 - 携带请求数据和上下文信息
 * @param <I> 请求数据类型
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
class ComponentContext<I> {
    private I requestData;
    private Map<String, Object> contextData = new ConcurrentHashMap<>();
    
    public ComponentContext(I requestData) {
        this.requestData = requestData;
    }
    
    public void putContext(String key, Object value) {
        contextData.put(key, value);
    }
    
    public <T> T getContext(String key, Class<T> type) {
        return type.cast(contextData.get(key));
    }
}

/**
 * 组件执行结果
 * @param <O> 输出数据类型
 */
@Data
class ComponentOutput<O> {
    private boolean success;
    private String errorCode;
    private String errorMessage;
    private O data;
    private List<ValidationResult> validationErrors;
    
    public static <O> ComponentOutput<O> success(O data) {
        ComponentOutput<O> output = new ComponentOutput<>();
        output.success = true;
        output.data = data;
        return output;
    }
    
    public static <O> ComponentOutput<O> failure(String errorCode, String errorMessage) {
        ComponentOutput<O> output = new ComponentOutput<>();
        output.success = false;
        output.errorCode = errorCode;
        output.errorMessage = errorMessage;
        return output;
    }
    
    public static <O> ComponentOutput<O> validationError(List<ValidationResult> errors) {
        ComponentOutput<O> output = new ComponentOutput<>();
        output.success = false;
        output.errorCode = "VALIDATION_FAILED";
        output.errorMessage = "参数校验失败";
        output.validationErrors = errors;
        return output;
    }
}

// ====== 组件注册中心 ======

class ComponentRegistry {
    private final Map<String, Component<?, ?>> components = new ConcurrentHashMap<>();
    
    public void register(Component<?, ?> component, String alias) {
        components.put(alias, component);
    }
    
    public <I, O> Component<I, O> getComponent(String alias) {
        Component<?, ?> component = components.get(alias);
        if (component == null) {
            throw new IllegalArgumentException("未注册的组件: " + alias);
        }
        @SuppressWarnings("unchecked")
        Component<I, O> typedComponent = (Component<I, O>) component;
        return typedComponent;
    }
    
    public Map<String, Class<?>> listComponents() {
        return components.entrySet().stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey, 
                e -> e.getValue().getClass()
            ));
    }
}

// ====== 工作流引擎 ======

class Workflow {
    private String id;
    private List<Step> steps = new ArrayList<>();
    
    public Workflow(String id) {
        this.id = id;
    }
    
    public Workflow addStep(String name, String componentAlias, Map<String, Object> config) {
        steps.add(new Step(name, componentAlias, config));
        return this;
    }
    
    public List<Step> getSteps() {
        return Collections.unmodifiableList(steps);
    }
    
    public String getId() {
        return id;
    }
    
    static class Step {
        private final String name;
        private final String componentAlias;
        private final Map<String, Object> config;
        
        public Step(String name, String componentAlias, Map<String, Object> config) {
            this.name = name;
            this.componentAlias = componentAlias;
            this.config = config;
        }
        
        public String getComponentAlias() {
            return componentAlias;
        }
        
        public Map<String, Object> getConfig() {
            return config;
        }
        
        public String getName() {
            return name;
        }
    }
}

class WorkflowEngine {
    private final ComponentRegistry registry;
    
    public WorkflowEngine(ComponentRegistry registry) {
        this.registry = registry;
    }
    
    @SuppressWarnings("unchecked")
    public <I, O> ComponentOutput<O> execute(Workflow workflow, ComponentContext<I> context) {
        Object currentData = context.getRequestData();
        ComponentContext<Object> currentContext = new ComponentContext<>(currentData);
        currentContext.getContextData().putAll(context.getContextData());
        
        for (Workflow.Step step : workflow.getSteps()) {
            Component<Object, Object> component = 
                (Component<Object, Object>) registry.getComponent(step.getComponentAlias());
            
            // 应用步骤配置到上下文
            step.getConfig().forEach(currentContext::putContext);
            
            ComponentOutput<Object> output = component.execute(currentContext);
            
            if (!output.isSuccess()) {
                return (ComponentOutput<O>) output;
            }
            
            // 更新当前数据和上下文
            currentData = output.getData();
            currentContext.setRequestData(currentData);
            currentContext.putContext("previousStep", step.getName());
        }
        
        return (ComponentOutput<O>) ComponentOutput.success(currentData);
    }
}

// ====== 校验框架核心 ======

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface ValidateRule {
    String type() default "NONE";
    int min() default Integer.MIN_VALUE;
    int max() default Integer.MAX_VALUE;
    String pattern() default "";
    String message() default "";
    String[] dependsOn() default {};
    Class<? extends ValidatorFunction> customValidator() default ValidatorFunction.None.class;
}

interface ValidatorFunction {
    ValidationResult validate(String fieldName, Object value, Object object);
    
    class None implements ValidatorFunction {
        @Override
        public ValidationResult validate(String fieldName, Object value, Object object) {
            return ValidationResult.valid();
        }
    }
}
// 新增注解：类级别跨字段校验
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
 @interface CrossFieldValidation {
    Class<? extends GroupValidator>[] validators() default {};
}

// 新增注解：字段间关系校验
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
 @interface FieldRelation {
    String dependsOn(); // 依赖字段名称
    String condition(); // 条件表达式
    String message() default "字段校验失败";
}

// 组合校验器接口
 interface GroupValidator {
    List<ValidationResult> validate(Object object);
}
@Data
class ValidationResult {
    private String field;
    private String message;
    private String errorCode;

    public static ValidationResult valid() {
        return new ValidationResult();
    }

    public static ValidationResult error(String field, String message) {
        ValidationResult result = new ValidationResult();
        result.field = field;
        result.message = message;
        return result;
    }

    public static ValidationResult error(String field, String message, String errorCode) {
        ValidationResult result = new ValidationResult();
        result.field = field;
        result.message = message;
        result.errorCode = errorCode;
        return result;
    }

    public boolean isValid() {
        return field == null;
    }
}

class ValidationComponent implements Component<Object, Object> {

    @Override
    public String getType() {
        return "ValidationComponent";
    }

    @Override
    public ComponentOutput<Object> execute(ComponentContext<Object> context) {
        Object request = context.getRequestData();
        List<ValidationResult> errors = new ArrayList<>();

        // 校验实体类的字段
        for (Field field : request.getClass().getDeclaredFields()) {
            ValidateRule rule = field.getAnnotation(ValidateRule.class);
            if (rule != null) {
                try {
                    field.setAccessible(true);
                    Object value = field.get(request);
                    errors.addAll(validateField(field.getName(), value, request, rule));
                } catch (IllegalAccessException e) {
                    errors.add(ValidationResult.error(field.getName(), "字段访问失败: " + e.getMessage()));
                }
            }
        }

        // 2. 新增跨字段注解校验
        errors.addAll(processCrossFieldAnnotations(request));

        // 3. 新增类级别校验注解处理
        errors.addAll(processClassLevelValidations(request));

        if (!errors.isEmpty()) {
            return ComponentOutput.validationError(errors);
        }

        return ComponentOutput.success(request);
    }

    private List<ValidationResult> validateField(String fieldName, Object value, Object object, ValidateRule rule) {
        List<ValidationResult> errors = new ArrayList<>();

        // 必填校验
        if ("REQUIRED".equals(rule.type())) {
            if (value == null || (value instanceof String && ((String) value).isEmpty())) {
                String message = rule.message().isEmpty() ? fieldName + "不能为空" : rule.message();
                errors.add(ValidationResult.error(fieldName, message, "REQUIRED"));
            }
        }

        // 长度校验
        if ("LENGTH".equals(rule.type()) && value instanceof String) {
            int length = ((String) value).length();
            if (length < rule.min() || length > rule.max()) {
                String message = rule.message().isEmpty() ?
                    fieldName + "长度必须在" + rule.min() + "到" + rule.max() + "之间" :
                    rule.message();
                errors.add(ValidationResult.error(fieldName, message, "LENGTH"));
            }
        }

        // 正则校验
        if ("REGEX".equals(rule.type()) && value instanceof String && !rule.pattern().isEmpty()) {
            if (!Pattern.matches(rule.pattern(), (String) value)) {
                String message = rule.message().isEmpty() ?
                    fieldName + "格式不正确" :
                    rule.message();
                errors.add(ValidationResult.error(fieldName, message, "REGEX"));
            }
        }

        // 自定义校验函数
        if (!rule.customValidator().equals(ValidatorFunction.None.class)) {
            try {
                ValidatorFunction validator = rule.customValidator().getDeclaredConstructor().newInstance();
                ValidationResult result = validator.validate(fieldName, value, object);
                if (!result.isValid()) {
                    errors.add(result);
                }
            } catch (Exception e) {
                errors.add(ValidationResult.error(fieldName, "自定义校验器执行失败: " + e.getMessage()));
            }
        }

        return errors;
    }


    // 新增方法：处理字段关系注解
    private List<ValidationResult> processCrossFieldAnnotations(Object object) {
        List<ValidationResult> errors = new ArrayList<>();
        Class<?> clazz = object.getClass();

        for (Field field : clazz.getDeclaredFields()) {
            FieldRelation relation = field.getAnnotation(FieldRelation.class);
            if (relation != null) {
                try {
                    field.setAccessible(true);
                    Object value = field.get(object);

                    // 获取依赖字段值
                    Field dependentField = clazz.getDeclaredField(relation.dependsOn());
                    dependentField.setAccessible(true);
                    Object dependentValue = dependentField.get(object);

                    // 解析表达式并校验
                    errors.addAll(evaluateRelation(
                            field.getName(),
                            value,
                            relation.condition(),
                            dependentValue,
                            relation.message()
                    ));
                } catch (Exception e) {
                    errors.add(ValidationResult.error(field.getName(),
                            "字段关系校验失败: " + e.getMessage()));
                }
            }
        }

        return errors;
    }

    // 新增方法：处理类级别校验
    private List<ValidationResult> processClassLevelValidations(Object object) {
        List<ValidationResult> errors = new ArrayList<>();
        CrossFieldValidation classAnnotation =
                object.getClass().getAnnotation(CrossFieldValidation.class);

        if (classAnnotation != null) {
            for (Class<? extends GroupValidator> validatorClass : classAnnotation.validators()) {
                try {
                    GroupValidator validator = validatorClass.getDeclaredConstructor().newInstance();
                    errors.addAll(validator.validate(object));
                } catch (Exception e) {
                    errors.add(ValidationResult.error("Class",
                            "类校验器执行失败: " + e.getMessage()));
                }
            }
        }
        return errors;
    }

    // 新增方法：表达式评估
    private List<ValidationResult> evaluateRelation(
            String fieldName, Object value, String condition,
            Object dependentValue, String message) {

        List<ValidationResult> errors = new ArrayList<>();

        try {
            boolean valid = false;

            switch (condition) {
                case "EQUALS":
                    valid = Objects.equals(value, dependentValue);
                    break;
                case "NOT_EQUALS":
                    valid = !Objects.equals(value, dependentValue);
                    break;
                case "GREATER_THAN":
                    if (value instanceof Number && dependentValue instanceof Number) {
                        double num1 = ((Number) value).doubleValue();
                        double num2 = ((Number) dependentValue).doubleValue();
                        valid = num1 > num2;
                    }
                    break;
                case "CONTAINS":
                    if (dependentValue != null && value != null) {
                        valid = dependentValue.toString().contains(value.toString());
                    }
                    break;
                // 可扩展其他条件
                default:
                    throw new IllegalArgumentException("未知条件: " + condition);
            }

            if (!valid) {
                errors.add(ValidationResult.error(fieldName, message));
            }
        } catch (Exception e) {
            errors.add(ValidationResult.error(fieldName, "表达式评估错误: " + e.getMessage()));
        }

        return errors;
    }
}

// ====== 业务对象定义 ======

@Data
class UserRegistrationRequest {
    @ValidateRule(type = "REQUIRED", message = "用户名不能为空")
    private String username;
    
    @ValidateRule(type = "REGEX", pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$", 
                 message = "密码必须包含大小写字母和数字")
    @FieldRelation(dependsOn = "username", condition = "NOT_EQUALS", message = "密码不能与用户名相同")
    private String password;
    @FieldRelation(dependsOn = "password", condition = "EQUALS", message = "两次密码输入不一致")
    private String passwordConfirm;
    
    @ValidateRule(type = "REGEX", pattern = "^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$", message = "邮箱格式不正确")
    private String email;
    
    @ValidateRule(type = "REGEX", pattern = "^\\d{4}-\\d{2}-\\d{2}$", message = "生日格式应为YYYY-MM-DD")
    private String birthDate;
    
    // 自定义校验 - 使用校验函数
    @ValidateRule(customValidator = UsernameAvailabilityValidator.class)
    private String customCheck;
}

class UsernameAvailabilityValidator implements ValidatorFunction {
    @Override
    public ValidationResult validate(String fieldName, Object value, Object object) {
        String username = (String) value;
        if (username != null && username.length() > 0) {
            // 实际实现中应该调用服务检查用户名是否可用
            boolean available = !username.equals("admin") && !username.equals("root");
            if (!available) {
                return ValidationResult.error(fieldName, "用户名已被占用", "USERNAME_TAKEN");
            }
        }
        return ValidationResult.valid();
    }
}

@Data
class UserRegistrationResponse {
    private String userId;
    private LocalDateTime createdAt;
    private String status;
    
    @Override
    public String toString() {
        return "用户ID: " + userId + ", 状态: " + status;
    }
}

@Data
class OrderRequest {
    @ValidateRule(type = "REQUIRED", message = "用户ID不能为空")
    private String userId;
    
    @ValidateRule(type = "REQUIRED", message = "商品列表不能为空")
    private List<String> items;
    
    @ValidateRule(type = "RANGE", min = 0, message = "总金额必须大于0")
    private Double totalAmount;
    
    @ValidateRule(type = "REQUIRED", message = "支付方式不能为空")
    private String paymentMethod;
    
    private String cardNumber;
}

@Data
class OrderResponse {
    private String orderId;
    private String status;
    private Double amount;
    private LocalDateTime createTime;
    
    @Override
    public String toString() {
        return "订单ID: " + orderId + ", 金额: " + amount + ", 状态: " + status;
    }
}

// ====== 业务组件实现 ======

class UserRegistrationComponent implements Component<UserRegistrationRequest, UserRegistrationResponse> {

    @Override
    public String getType() {
        return "UserRegistration";
    }

    @Override
    public ComponentOutput<UserRegistrationResponse> execute(ComponentContext<UserRegistrationRequest> context) {
        UserRegistrationRequest request = context.getRequestData();
        
        // 模拟业务处理
        UserRegistrationResponse response = new UserRegistrationResponse();
        response.setUserId("user-" + UUID.randomUUID().toString().substring(0, 8));
        response.setCreatedAt(LocalDateTime.now());
        response.setStatus("ACTIVE");
        
        // 模拟日志记录
        context.putContext("userId", response.getUserId());
        context.putContext("status", response.getStatus());
        
        return ComponentOutput.success(response);
    }
}

class OrderProcessingComponent implements Component<OrderRequest, OrderResponse> {

    @Override
    public String getType() {
        return "OrderProcessing";
    }

    @Override
    public ComponentOutput<OrderResponse> execute(ComponentContext<OrderRequest> context) {
        OrderRequest request = context.getRequestData();
        
        // 模拟业务处理
        OrderResponse response = new OrderResponse();
        response.setOrderId("order-" + System.currentTimeMillis());
        response.setAmount(request.getTotalAmount());
        response.setCreateTime(LocalDateTime.now());
        
        // 支付处理模拟
        String method = request.getPaymentMethod();
        if ("CREDIT_CARD".equals(method)) {
            response.setStatus("PAYMENT_PENDING");
        } else if ("PAYPAL".equals(method)) {
            response.setStatus("PAID");
        } else {
            response.setStatus("NEW");
        }
        
        return ComponentOutput.success(response);
    }
}

class PaymentProcessingComponent implements Component<Object, Object> {

    @Override
    public String getType() {
        return "PaymentProcessing";
    }

    @Override
    public ComponentOutput<Object> execute(ComponentContext<Object> context) {
        // 实际中处理支付
        boolean async = context.getContext("async", Boolean.class) != null 
            ? context.getContext("async", Boolean.class)
            : false;
        
        if (async) {
            // 返回占位符
            return ComponentOutput.success("PAYMENT_IN_PROGRESS");
        }
        
        // 模拟支付处理
        return ComponentOutput.success("PAYMENT_COMPLETED");
    }
}

// ====== 技术组件实现 ======

class LoggingComponent implements Component<Object, Object> {

    @Override
    public String getType() {
        return "Logging";
    }

    @Override
    public ComponentOutput<Object> execute(ComponentContext<Object> context) {
        // 从上下文获取配置
        String logLevel = context.getContext("logLevel", String.class);
        if (logLevel == null) logLevel = "DEBUG";
        
        Object data = context.getRequestData();
        System.out.printf("[%s] 组件执行日志: %s | 上下文: %s\n", logLevel, data, context.getContextData());
        
        return ComponentOutput.success(data);
    }
}

class EncryptionComponent implements Component<Object, Object> {

    @Override
    public String getType() {
        return "Encryption";
    }

    @Override
    public ComponentOutput<Object> execute(ComponentContext<Object> context) {
        Object data = context.getRequestData();
        
        // 实际实现会进行加密处理
        if (data instanceof String) {
            String encrypted = "ENCRYPTED[" + data + "]";
            System.out.println("数据已加密: " + encrypted);
            return ComponentOutput.success(encrypted);
        }
        
        return ComponentOutput.success(data);
    }
}

class CachingComponent implements Component<Object, Object> {
    private final CacheManager cacheManager;
    
    public CachingComponent(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public String getType() {
        return "Caching";
    }

    @Override
    public ComponentOutput<Object> execute(ComponentContext<Object> context) {
        Object data = context.getRequestData();
        int ttl = context.getContext("ttl", Integer.class) != null 
            ? context.getContext("ttl", Integer.class)
            : 300;
        
        String cacheKey = generateCacheKey(context);
        ComponentOutput<?> cached = cacheManager.get(cacheKey);
        if (cached != null) {
            System.out.println("💾 缓存命中: " + cacheKey);
            return ComponentOutput.success(cached.getData());
        }
        
        System.out.println("⚠️ 缓存未命中: " + cacheKey);
        cacheManager.put(cacheKey, ComponentOutput.success(data), ttl);
        return ComponentOutput.success(data);
    }
    
    private String generateCacheKey(ComponentContext<Object> context) {
        return context.getRequestData().getClass().getSimpleName() + ":" 
            + context.getRequestData().hashCode();
    }
}

class AsyncExecutorComponent implements Component<Object, Object> {

    @Override
    public String getType() {
        return "AsyncExecutor";
    }

    @Override
    public ComponentOutput<Object> execute(ComponentContext<Object> context) {
        // 在实际实现中会异步执行后续组件
        return ComponentOutput.success(context.getRequestData());
    }
}

// ====== 缓存管理 ======

class CacheManager {
    private final Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
    private final ScheduledExecutorService cleanupScheduler = 
        Executors.newScheduledThreadPool(1);
    
    public CacheManager() {
        // 每5分钟清理一次过期缓存
        cleanupScheduler.scheduleAtFixedRate(this::cleanup, 5, 5, TimeUnit.MINUTES);
    }
    
    public void put(String key, ComponentOutput<?> value, int ttlSeconds) {
        cache.put(key, new CacheEntry(value, System.currentTimeMillis() + ttlSeconds * 1000L));
    }
    
    public ComponentOutput<?> get(String key) {
        CacheEntry entry = cache.get(key);
        if (entry != null && entry.isValid()) {
            return entry.getValue();
        }
        return null;
    }
    
    private void cleanup() {
        long now = System.currentTimeMillis();
        cache.values().removeIf(entry -> !entry.isValid(now));
    }
    
    @Data
    @AllArgsConstructor
    static class CacheEntry {
        private ComponentOutput<?> value;
        private long expiry;
        
        public boolean isValid() {
            return isValid(System.currentTimeMillis());
        }
        
        public boolean isValid(long timestamp) {
            return expiry > timestamp;
        }
    }
}